/**
 *   Wechaty - https://github.com/wechaty/wechaty
 *
 *   @copyright 2016-now Huan LI <zixia@zixia.net>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */
import 'dotenv/config.js'
import {ChatCompletion,setEnvVariable} from "@baiducloud/qianfan";

import {
    WechatyBuilder,
    ScanStatus,
    log,
}                     from 'wechaty'
import qrcodeTerminal from 'qrcode-terminal'
import request from "request";

const AK = "XUuPlI1JxhT8b2Uknsg35B5Q"
const SK = "kWWQbgMverLj2GoDzcFjciRii5oQeV8B"
// setEnvVariable('QIANFAN_ACCESS_KEY','XUuPlI1JxhT8b2Uknsg35B5Q');
// setEnvVariable('QIANFAN_SECRET_KEY','kWWQbgMverLj2GoDzcFjciRii5oQeV8B');

const client = new  ChatCompletion();
var userList = [];


function onScan (qrcode, status) {
    if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
        qrcodeTerminal.generate(qrcode, { small: true })  // show qrcode on console

        const qrcodeImageUrl = [
            'https://wechaty.js.org/qrcode/',
            encodeURIComponent(qrcode),
        ].join('')

        log.info('StarterBot', 'onScan: %s(%s) - %s', ScanStatus[status], status, qrcodeImageUrl)

    } else {
        log.info('StarterBot', 'onScan: %s(%s)', ScanStatus[status], status)
    }
}

function onLogin (user) {
    log.info('StarterBot', '%s login', user)
}

function onLogout (user) {
    log.info('StarterBot', '%s logout', user)
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken() {

    let options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
    }
    return new Promise((resolve, reject) => {
        request(options, (error, response) => {
            if (error) { reject(error) }
            else { resolve(JSON.parse(response.body).access_token) }
        })
    })
}

async function onMessage (msg) {
    console.log('msg',msg)

    var text = msg.text()
    var name = msg.talker().name()

    if (!userList.includes(name)){
        if (text === '1752'){
            userList.push(name);
            await msg.say('欢迎'+name+'体验');
        }
    }else {
        if(text === 'exit'){
            await msg.say('欢迎'+name+'下次体验，再见');
            userList = userList.filter(item => item !== name);
        }else {
            var options = {
                'method': 'POST',
                'url': 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-tiny-8k?access_token=' + await getAccessToken(),
                'headers': {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    "user_id": name,
                    "messages": [
                        {
                            "role": "user",
                            "content":text
                        }
                    ],
                    "temperature": 0.95,
                    "top_p": 0.7,
                    "penalty_score": 1
                })
            };
            console.log('options',options)
            request(options, function (error, response) {
                if (error) throw new Error(error);
                msg.say(JSON.parse(response.body).result);
            });

        }
    }


    // if (msg.text() === 'ding') {
    //     await msg.say('dong')
    // }
}

const bot = WechatyBuilder.build({
    name: 'ding-dong-bot',
})

bot.on('scan',    onScan)
bot.on('login',   onLogin)
bot.on('logout',  onLogout)
bot.on('message', onMessage)

bot.start()
    .then(() => log.info('StarterBot', 'Starter Bot Started.'))
    .catch(e => log.error('StarterBot', e))
console.log("启动服务")
